package com.tzxs.pay.main.installment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tzxs.pay.R;
import com.tzxs.pay.databinding.ActivityInstallmentBinding;
import com.tzxs.pay.databinding.InstallDialogBinding;
import com.tzxs.pay.main.base.BaseActivity;
import com.tzxs.pay.main.base.OnMultiClickListener;
import com.tzxs.pay.main.bill.detail.CollAndInstallDetailActivity;
import com.tzxs.pay.util.ISharedPreference;
import com.tzxs.pay.util.StatusBarColorSetter;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * 分期付款
 */
public class InstallmentActivity extends BaseActivity<ActivityInstallmentBinding> implements Toolbar.OnMenuItemClickListener {
    private OnMultiClickListener onMultiClickListener = new OnMultiClickListener() {
        @Override
        public void onMultiClick(View v) {
            switch (v.getId()) {
                //顾客
                case R.id.customer_rad:
                case R.id.installment_customer_lay:
                    clearChoose();
                    dataBinding.customerRad.setSelected(true);
                    break;
                //商家
                case R.id.merchants_rad:
                case R.id.installment_merchants_lay:
                    clearChoose();
                    dataBinding.merchantsRad.setSelected(true);
                    break;
                //扫码分期
                case R.id.scan_install_btn:
                    if (dataBinding.amount.getText().toString().isEmpty()) {
                        Snackbar.make(v, "请输入收款金额!", Snackbar.LENGTH_SHORT).show();
                        return;
                    }
                    if (dataBinding.chooseInstallmentMonth.getText().toString().isEmpty()) {
                        Snackbar.make(v, "请选择分期数!", Snackbar.LENGTH_SHORT).show();
                        return;
                    }
                    requestScanPermission();
                    break;
                //选择分期
                case R.id.choose_installment_month:
                    intBottomSheetDialog();
                    break;
            }
        }
    };
    private static final String TAG = InstallmentActivity.class.getSimpleName();
    private static final int SCAN_CODE = 100;
    private String time;//时限
    private RxPermissions permissions;
    private ProgressDialog dialog;//dialog
    private ScanViewModel model;

    @Override
    protected Activity getChildActivity() {
        return this;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_installment;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarColorSetter.setStatusBarColor(this, getResources().getColor(R.color.colorWhite));
        permissions = new RxPermissions(this);
        model = ViewModelProviders.of(this).get(ScanViewModel.class);
        dataBinding.installmentToolbar.setTitle("");
        setSupportActionBar(dataBinding.installmentToolbar);
        dataBinding.installmentToolbar.setNavigationOnClickListener(v -> onBackPressed());
        dataBinding.installmentToolbar.setOnMenuItemClickListener(this);
        dataBinding.customerRad.setOnClickListener(onMultiClickListener);
        dataBinding.customerRad.setSelected(true);//默认选择手续费承担方
        dataBinding.merchantsRad.setOnClickListener(onMultiClickListener);
        dataBinding.scanInstallBtn.setOnClickListener(onMultiClickListener);
        dataBinding.chooseInstallmentMonth.setOnClickListener(onMultiClickListener);
        dataBinding.installmentCustomerLay.setOnClickListener(onMultiClickListener);
        dataBinding.installmentMerchantsLay.setOnClickListener(onMultiClickListener);
        //下单成功
        model.dialogText.observe(InstallmentActivity.this, s -> {
            if (s == null) {
                if (dialog != null) {
                    dialog.dismiss();
                }
            } else {
                //我的dialog需要一个标题,所以我需要一个接口方法来获取标题
                dialog = ProgressDialog.show(InstallmentActivity.this, s, "正在等待付款...", false, false);
            }
        });
        model.snackText.observe(this, s ->
                Snackbar.make(dataBinding.installmentToolbar, s, Snackbar.LENGTH_SHORT).show());
    }

    /**
     * 清除选择
     */
    private void clearChoose() {
        dataBinding.merchantsRad.setSelected(false);
        dataBinding.customerRad.setSelected(false);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.installment_bill, menu);
        return true;
    }

    /**
     * 申请二维码扫描需要的权限
     */
    @SuppressLint("CheckResult")
    private void requestScanPermission() {
        permissions.requestEach(Manifest.permission.CAMERA).subscribe(permission -> {

            if (permission.granted) {
                scanCode();
            } else if (permission.shouldShowRequestPermissionRationale) {
                Toast.makeText(InstallmentActivity.this, "扫描二维码需要相机权限!", Toast.LENGTH_SHORT).
                        show();

            } else {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivity(intent);

            }
        });

    }

    //开始扫描二维码
    private void scanCode() {
        Intent scanIntent = new Intent(this, CaptureActivity.class);

        startActivityForResult(scanIntent, SCAN_CODE);
    }

    //显示bottomDialog
    private void intBottomSheetDialog() {
        BottomSheetDialog dialog = new BottomSheetDialog(this);

        InstallDialogBinding binding = DataBindingUtil.inflate(getLayoutInflater(),
                R.layout.install_dialog, null, false);
        dialog.setContentView(binding.getRoot());

        binding.three.setOnClickListener(v -> {
            dataBinding.chooseInstallmentMonth.setText(((TextView) v).getText().toString());
            dialog.dismiss();
        });
        binding.six.setOnClickListener(v -> {
            dataBinding.chooseInstallmentMonth.setText(((TextView) v).getText().toString());
            dialog.dismiss();
        });
        binding.twelve.setOnClickListener(v -> {
            dataBinding.chooseInstallmentMonth.setText(((TextView) v).getText().toString());
            dialog.dismiss();
        });
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {

        if (item.getItemId() == R.id.install_bill) {
            Intent intent = new Intent(this, InstallmentBillActivity.class);
            startActivity(intent);
            return true;
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult: 走这个方法了么:");
        if (requestCode == SCAN_CODE) {
            if (data != null) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    int money;
                    if (dataBinding.customerRad.isSelected()) {
                        money = 0;
                    } else {
                        money = 100;
                    }
                    model.startScanInstall(dataBinding.amount.getText().toString(), getInstallNum(), result, money, () -> {
                        //成功分期后 暂停dialog
                        dialog.dismiss();
                        String content = "花呗分期成功  " + dataBinding.amount.getText().toString() + getCurrentTime();
                        model.startGt(ISharedPreference.getInstance(getApplication()).getCid(), "天择可付推送提醒", content, () -> {

                        });
                        Intent intent = new Intent(InstallmentActivity.this, CollAndInstallDetailActivity.class);
                        intent.putExtra("orderId", Objects.requireNonNull(model.bean.get()).getOut_trade_no());
                        intent.putExtra("needPrint", true);
                        startActivity(intent);
                    });
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {

                    Toast.makeText(this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }

            }
        }
    }

    //获得分期数
    private int getInstallNum() {
        int month = 0;
        switch (dataBinding.chooseInstallmentMonth.getText().toString()) {
            case "3个月":
                month = 3;
                break;
            case "6个月":
                month = 6;
                break;
            case "12个月":
                month = 12;
                break;
        }

        return month;
    }


    //获取当前时间
    private String getCurrentTime() {
        SimpleDateFormat simpleDateFormat = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
        simpleDateFormat.applyPattern("MM-dd HH:mm:SS");

        return simpleDateFormat.format(new Date());
    }
}
